import React, { useEffect } from 'react';
import type { Tag, Dispatch, IRoute } from 'umi';
import { Tabs } from 'antd';
import { Route } from 'react-router-dom';
import { history, useSelector } from 'umi';
import _ from 'lodash'
import styles from './index.less';

export interface TabsViewProps {
  route: IRoute;
  activeKey: string;
  tags: Tag[];
  dispatch: Dispatch;
}

const { TabPane } = Tabs;

const IndexPage: React.FC<TabsViewProps> = React.memo((props) => {
  const {tags, activeKey, dispatch, route } = props;
  const tagsModels= useSelector(s => s.tagsModel);
  useEffect(() => {
    const getTitleFromRoute = (path: string) => {
      let titleRoute = filterType(path, props.route.routes)
      // 没有权限的页面访问不到

      if (titleRoute[0].unaccessible === true) {
        return '权限页面';
      }
      return titleRoute[0].name;
    };

    history.listen((location) => {
      // location is an object like window.location
      dispatch({
        type: 'tagsModel/addTag',
        payload: {
          key: location.pathname,
          title: getTitleFromRoute(location.pathname),
          active: true,
          path: location.pathname,
          query: location.query
        },
      });
    });
  }, []);

  useEffect(() => {
    const dom = document.getElementsByClassName('ant-tabs-tab-btn');
    const tabDoms = Array.from(dom);
    // 给每个tabs设置title
    tabDoms.forEach((item: any) => {
      item.title = item.innerText;
    });
  }, [tags]);

  const tabOnEdit = (targetKey: React.MouseEvent | React.KeyboardEvent | string, action: 'add' | 'remove') => {
    if (action === 'remove') {
      dispatch({ type: 'tagsModel/removeTag', payload: targetKey });
      const index = tags.findIndex(t => t.key === activeKey);
      if (targetKey !== activeKey) {
        history.push(tags[index ].path ?? '/dashboard')
      } else {
        history.push(tags[index - 1 ].path ?? '/dashboard')
      }
    }
  };

  const tabOnChange = (selectKey: string) => {
    const url = getTags(selectKey)
    history.push({
      pathname: url.path ?? '/dashboard',
      query: url.query
    });
    props.dispatch({ type: 'tagsModel/updateActive', payload: selectKey });
  };
  // 获取dva中的tagsModel拿到参数
  const getTags = (key) => {
    return tagsModels.filter(item => item.key === key)[0]
  }
  const filterType = (path:string, routes:any) => {
    // 匹配是否是父子菜单/^\/[\w-]+\/[\w-]+$/
    const regex = (/^\/([\w-]+)\/[\w-]+$/).exec(path)?.[1];

    if(regex) {
      const arr:any = routes?.filter((r:any) => {
        return r.path === '/' + regex
      })
      return arr[0].routes?.filter((r:any) => {
        // 如果是动态路由，匹配非动态部分
        if (r.path?.includes(':')) {
          return path.includes(r.path.split(':')[0]);
        }
        return r.path === path;
      }) ?? [];
    } else {
      return routes?.filter((r:any) => {
        // 如果是动态路由，匹配非动态部分
        if (r.path?.includes(':')) {
          return path.includes(r.path.split(':')[0]);
        }
        return r.path === path;
      }) ?? [];
    }
  }

  const getPathComponent = (path: string) => {
    const arrs = filterType(path, props.route.routes)[0]
    return arrs.component;
  };

  // 使用正则表达式获取 transform数值
  const getDomTransformData = () => {
    const dom = (document.getElementsByClassName('ant-tabs-nav-list')[0] as any).style.transform;
    const regx = /\((\S*)p/;
    const strData = regx.exec(dom)![1];
    return Number(strData);
  };

  // tabs 点击左箭头
  const clickTabsLeftBtn = () => {
    const tabsNavListWidth = (document.getElementsByClassName('ant-tabs-nav-list')[0] as any).offsetWidth;
    const tabsNavWidth = (document.getElementsByClassName('ant-tabs-nav-wrap')[0] as any).offsetWidth;
    const strData = getDomTransformData();


    if (tabsNavListWidth - (Math.abs(strData) + tabsNavWidth) < 200 && tabsNavListWidth >= tabsNavWidth) {
      (document.getElementsByClassName('ant-tabs-nav-list')[0] as any).style.transform = `translate(${
        Number(strData) - (tabsNavListWidth - (Math.abs(strData) + tabsNavWidth) + 20)
      }px, 0px)`;
    }
    // if (Math.abs(strData)+ tabsNavWidth + 100<tabsNavListWidth&&tabsNavListWidth>=tabsNavWidth) {
    //   (document.getElementsByClassName(
    //     'ant-tabs-nav-list',
    //   )[0] as any).style.transform = `translate(${Number(strData) - 100}px, 0px)`;
    // }

    if (Math.abs(strData) < tabsNavListWidth - (tabsNavWidth + 100)) {
      (document.getElementsByClassName('ant-tabs-nav-list')[0] as any).style.transform = `translate(${
        Number(strData) - 100
      }px, 0px)`;
    }
  };
  // tabs 点击右箭头
  const clickTabsRightBtn = () => {
    const tabsNavListWidth = (document.getElementsByClassName('ant-tabs-nav-list')[0] as any).offsetWidth;
    const strData = getDomTransformData();

    if (Math.abs(strData) > 100) {
      (document.getElementsByClassName('ant-tabs-nav-list')[0] as any).style.transform = `translate(${
        Number(strData) + 100
      }px, 0px)`;
    } else {
      (document.getElementsByClassName('ant-tabs-nav-list')[0] as any).style.transform = `translate(0px, 0px)`;
    }
  };
  const onTabClick = (key: any, event: any) => {
    console.log('key', key, event);
  };

  return (
    <div className={styles.tabsBox}>
      <Tabs
        activeKey={activeKey}
        type="editable-card"
        hideAdd={true}
        onEdit={tabOnEdit}
        onChange={tabOnChange}
        onTabClick={onTabClick}
        // destroyInactiveTabPane
        tabBarExtraContent={{
          left: (
            <div
              className={styles.tabsLeftButton}
              onClick={() => {
                clickTabsLeftBtn();
              }}
            >
              <div className={styles.tabsLeftButtonImg} />
            </div>
          ),
          right: (
            <>
              <div
                className={styles.tabsRightButton}
                onClick={() => {
                  clickTabsRightBtn();
                }}
              >
                <div className={styles.tabsRightButtonImg} />
              </div>
              <div className={styles.dropDownArrow}>
                <div className={styles.dropDownArrowImg} />
              </div>
            </>
          ),
        }}
        tabBarGutter={2}
      >
        {tags.length &&
          tags.map((tag) => {
            return (
              <TabPane tab={tag.title} key={tag.key} closable={tag.key !== '/dashboard'}>
                <Route key={tag.key} component={getPathComponent(tag.path!)} />
              </TabPane>
            );
          })}
      </Tabs>
    </div>
  );
});
export default IndexPage;
